package com.gec.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.gec.common.BaseContext;
import com.gec.entity.AddressBook;
import com.gec.mapper.AddressBookMapper;
import com.gec.service.AddressBookService;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

/**
 * <p>
 *
 * </p>
 *
 * @author : [chenxys]
 * @version : [v1.0]
 * @createTime : [2022/7/14 20:07]
 */
@Service
public class AddressBookServiceImpl extends ServiceImpl<AddressBookMapper, AddressBook> implements AddressBookService {
    @Override
    public List<AddressBook> listAll() {
        // 当前登录用户ID
        Long currentId = BaseContext.getCurrentId();
        // 构造条件
        LambdaQueryWrapper<AddressBook> addressBookLambdaQueryWrapper = new LambdaQueryWrapper<>();
        // 构造查询条件
        addressBookLambdaQueryWrapper.eq(AddressBook::getUserId,currentId);
        // 构造排序条件
        addressBookLambdaQueryWrapper.orderByAsc(AddressBook::getUpdateTime);
        // 查询
        return this.list(addressBookLambdaQueryWrapper);
    }

    @Override
    public AddressBook getDefaultAddressBook() {
        LambdaQueryWrapper<AddressBook> addressBookLambdaQueryWrapper = new LambdaQueryWrapper<>();
        // 构造条件 --> 默认地址
        addressBookLambdaQueryWrapper.eq(AddressBook::getIsDefault,1);
        // 用户ID
        addressBookLambdaQueryWrapper.eq(AddressBook::getUserId,BaseContext.getCurrentId());
        // 查询
        return this.getOne(addressBookLambdaQueryWrapper);
    }

    @Override
    public AddressBook getOneWithId(Long id) {
        LambdaQueryWrapper<AddressBook> addressBookLambdaQueryWrapper = new LambdaQueryWrapper<>();
        // 构造条件
        addressBookLambdaQueryWrapper.eq(AddressBook::getId,id);
        // 查询
        return this.getOne(addressBookLambdaQueryWrapper);
    }

    @Override
    @Transactional
    public void updateAddressBook(AddressBook addressBook) {
        this.updateById(addressBook);
    }

    @Override
    @Transactional
    public void saveAddressBook(AddressBook addressBook) {
        this.save(addressBook);
    }

    @Override
    @Transactional
    public void updateDefaults(AddressBook addressBook) {
        // 将当前用户的所有地址状态都设为0
        LambdaUpdateWrapper<AddressBook> addressBookLambdaUpdateWrapper = new LambdaUpdateWrapper<>();
        addressBookLambdaUpdateWrapper.eq(AddressBook::getUserId,BaseContext.getCurrentId());
        // 赋值为0
        addressBookLambdaUpdateWrapper.set(AddressBook::getIsDefault,0);
        // 更新
        this.update(addressBookLambdaUpdateWrapper);
        // 将传入的新地址ID设置为默认
        addressBook.setIsDefault(1);
        this.updateById(addressBook);
    }
}
